#!/usr/bin/env python3
import requests
import os


def write2file(path, content):
    with open(path, 'a') as f:
        f.write(content)


class UmengHelper():
    def __init__(self) -> None:
        self.mSession = requests.session()
        self.cookie = 'ctoken=BMppT7huGZOYukZA9aWg7rZL; cna=m1MiGFfn8ksCAXDjog8/ZqOY; XSRF-TOKEN=98173618-badb-4383-90d3-0d7b7cbe8dff; channeldata_session=cbc9ee1a-ae27-4401-af3c-51a20bd6193f; xlly_s=1; isg=BAoK5nGZYdp5oe1yoSg-pJ6kW_ms-45VObBPspRClN3oR6kBZI5rZU7xV7Obtwbt'
        cookie_dict = {i[:i.find('=')]:i[i.find('=')+1:] for i in self.cookie.split("; ")}
        c = requests.cookies.RequestsCookieJar()
        for k,v in cookie_dict.items():
            c.set(k, v, path='/', domain='.umeng.com')
        self.mSession.cookies.update(c)


    def getoneChannelInfo(self, game = False, startDate = '2020-07-01', endDate = '2020-07-31', channelId = '5f003b58ed3b44071c008824'):
        url = 'https://mobile.umeng.com/ht/api/v3/channel/user/detail'
        para={
            'game':game,
            'pageSize':'40',
            'startDate': startDate,
            'endDate':endDate,
            'channelId': channelId,
        }

        resp = self.mSession.get(url, params = para)
        #print(resp.text)
        respj = resp.json()
        for daydate in respj['data']['list']:
            if daydate['date'] == '时段内均值':
                continue
            if daydate['active'] == 0 and daydate['install_new'] == 0:
                continue
            content = '{},{},{},{}\n'.format(respj['data']['title'], daydate['date'], daydate['install_new'], daydate['active'])
            write2file(path, content)



    def getsummary(self, type='app', page=1, game=False, channelId = '5efe9ba3167edd5ce300007b'):
        url = "https://mobile.umeng.com/ht/api/v3/channel/user/summary"

        para = {
            'type':type,
            'page':page,
            'game':game,
            'pageSize':'30',
            'channelId': channelId,
            'startDate':'2020-08-11',
        }

        resp = self.mSession.get(url, params = para).json()
        return resp



    def getallInfo(self, d,startDate, endDate):
        channelids = []
        while True:
            page = 1
            summary = self.getsummary(d['type'], page=page, game = d['game'], channelId = d['channelId'])
            if summary['code'] == 200:
                for c in summary['data']['list']:
                    channelids.append(c['channelId'])
                if summary['data']['count'] == len(channelids):
                    break
                else:
                    page+=1
            else:
                print('get summary failed')
                return

        for c in channelids:
            self.getoneChannelInfo(d['game'], startDate = startDate, endDate=endDate, channelId = c,)


    def list(self, startDate, endDate):
        url = "https://mobile.umeng.com/ht/api/v3/channel/user/list"
        resp = self.mSession.get(url).json()
        if resp['code'] == 200:
            for d in resp['data']:
                if d['type'] != 'user':
                    print(d)
                    self.getallInfo(d,startDate, endDate)


        else:
            print('list failed')



if __name__ == "__main__":
    path = 'allinfo.csv'
    if os.access(path, os.F_OK):
        os.unlink(path)
    t = UmengHelper()
    t.list(startDate='2020-10-01', endDate='2020-10-31')
